package com.hzhk.happyrent.network;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.widget.Toast;

import com.tamic.novate.callback.RxStringCallback;
import com.hzhk.happyrent.ui.dialog.LoadingDialog;
import com.tamic.novate.util.NetworkUtil;

/**
 * User: hzhk(1097282555@qq.com)
 * Date: 2017/11/28
 * Time: 14:24
 * progject: hzk
 * Describe： ${Describe}
 */
public abstract class MyStringTransResponse extends RxStringCallback {

    private Dialog progress;
    private Context context;

    public MyStringTransResponse(Context context) {
        this.context = context;
        progress = new LoadingDialog((Activity) context,"");
    }

    @Override
    public void onNext(Object tag, String response) {
        String message=regexChange(response);
        onNext(message);
    }
    public abstract void onNext(String response);
    /**
     * 对输入的字符串进行处理
     * @param input 传入的需要处理的字符串
     * @return
     */
    private String regexChange(String input) {
        String result=input;
        if(result.contains("\"data\":\\[\\]")){
            result=result.replaceFirst("\"data\":\\[\\]","\"data\":\\{\\}");
        }else if(result.contains("\"user_info\":\\[\\]")){
            result=result.replaceFirst("\"user_info\":\\[\\]","\"user_info\":\\{\\}");
        }
        return result;
    }

    @Override
    public void onStart(Object tag) {
        super.onStart(tag);
        if (!NetworkUtil.isNetworkAvailable(context)) {
            Toast.makeText( context, "网络异常",Toast.LENGTH_SHORT).show();
            onCompleted(tag);
            return;
        }
        if (progress != null){
            if (progress.isShowing()) {
                progress.dismiss();
            }
            progress.show();
        }
    }


    @Override
    public void onCompleted(Object tag) {
        super.onCompleted(tag);
        if (progress != null && progress.isShowing()) {
            progress.dismiss();
        }
    }

}
